package com.zaofan.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zaofan.bean.*;
import com.zaofan.cache.CacheManage;
import com.zaofan.dao.ProductTypeDao;
import com.zaofan.utils.C3p0DataSourceUtils;
import org.apache.commons.beanutils.BeanUtils;

import com.zaofan.exception.ServiceException;
import com.zaofan.service.AdminService;
import com.zaofan.service.ShopBuilderService;
import com.zaofan.service.ShopPayLableService;
import com.zaofan.service.ShopService;
import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.WebUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

@WebServlet("/shop")
public class ShopController extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private ShopService shopService = new ShopService();
	private ShopPayLableService payLableService = new ShopPayLableService();
	private ShopBuilderService shopBuilderService = new ShopBuilderService();
	private AdminService adminService = new AdminService();

	protected void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Map<String, Object> params = new HashMap<>();
			Enumeration<String> enumeration = request.getParameterNames();
			while (enumeration.hasMoreElements()) {
				String name = enumeration.nextElement();
				if ("action".equals(name)) {
					continue;
				}
				Object value = request.getParameter(name);
				params.put(name, value);
			}
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			if (admin.getCityId() != 0) {
				params.put("cityId", admin.getCityId());
			}
			List<Shop> shops = shopService.findAll(params);
			Long count = shopService.count(params);
			JsonUtils.writeSuccessPageJson("查询成功", shops, count, response);
			shops.clear();
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}

	public void GetShopBanner(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Map<String, Object> datas = new HashMap<>();
			datas.put("banner", CacheManage.shopsBanner);
			JsonUtils.writeSuccessJson("查询成功", datas, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询失败", response);
		}
		JsonUtils.writeBeanFailJson("查询失败!!" + ",未知错误", response);
	}

	public void GetShopBanner1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			Map<String, Object> datas = new HashMap<>();
			datas.put("banner", CacheManage.shopsBanner1);
			JsonUtils.writeSuccessJson("查询成功", datas, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询失败", response);
		}
		JsonUtils.writeBeanFailJson("查询失败!!" + ",未知错误", response);
	}

	protected void open(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Integer builderId = Integer.valueOf(request
					.getParameter("builderId"));
			List<Shop> shops = shopService.findByBuilderId(builderId);
			JsonUtils.writeSuccessJson("查询成功", shops, response);
			shops.clear();
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeListFailJson("参数错误!!", response);
		}
		JsonUtils.writeListFailJson("查询失败!!", response);
	}

	protected void add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			Shop shop = WebUtils.write2bean(request, Shop.class);
			String[] payLableId = request.getParameterValues("payLableId");
			String[] builderIds = request.getParameterValues("builderIds");
			shopService.add(shop, payLableId, builderIds);
			JsonUtils.writeSuccessJson("添加成功", "", response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("添加失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeListFailJson("添加失败!!", response);
	}

	protected void addManage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			Admin admin = WebUtils.write2bean(request, Admin.class);
			adminService.addShopAdmin(admin);
			JsonUtils.writeSuccessJson("添加成功", "", response);
			return;
		} catch (ServiceException e) {
			JsonUtils.writeFailJson(e.getMessage(), response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("添加失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeListFailJson("添加失败!!", response);
	}

	protected void update(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			Shop shop = WebUtils.write2bean(request, Shop.class);
			String[] payLableId = request.getParameterValues("payLableId");
			String[] builderIds = request.getParameterValues("builderIds");
			shopService.update(shop, payLableId, builderIds);
			JsonUtils.writeSuccessJson("修改成功", "", response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("修改失败!!" + e.getMessage(), response);
		}
		JsonUtils.writeListFailJson("修改失败!!", response);
	}

	protected void get(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String id_s = request.getParameter("id");
			Integer id = Integer.valueOf(id_s);
			Shop shop = shopService.findById(id);
			ShopDO shopDO = new ShopDO();
			BeanUtils.copyProperties(shopDO, shop);
			List<ShopPayLable> lables = payLableService.findByShopId(shop
					.getId());
			shopDO.setPayLables(lables);
			List<ShopBuilder> builders = shopBuilderService.findByShopId(shop
					.getId());
			shopDO.setBuilders(builders);
			JsonUtils.writeSuccessJson("查询成功", shopDO, response);
			return;
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询成功!!" + e.getMessage(), response);
		}
		JsonUtils.writeBeanFailJson("查询成功!!", response);
	}

	protected void state(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String temp = request.getParameter("id");
		try {
			Integer id = Integer.valueOf(temp);
			Shop shop = shopService.findById(id);
			shop.setState(shop.getState() == 0 ? 1 : 0);
			shopService.setShopState(shop);
			JsonUtils.writeSuccessJson("更新成功!!", "", response);
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeFailJson("参数错误!!", response);
		}
		JsonUtils.writeFailJson("更新失败!!", response);
	}


    protected void addSendDate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String sDate = request.getParameter("sdate");
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        try {
            int i = qr.update("insert into sendDate(sdate) values(?) ",new Object[]{sDate});
            JsonUtils.writeSuccessJson("添加成功", "", response);
        } catch (SQLException e) {
            e.printStackTrace();
            if (e.getErrorCode() == 1062)
                JsonUtils.writeBeanFailJson("该日期已存在", response);
            else
                JsonUtils.writeBeanFailJson("添加失败", response);
        }
    }
    protected void delSendDate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        try {
            int i = qr.update("delete from sendDate where id = ? ",new Object[]{Integer.valueOf(id)});
            JsonUtils.writeSuccessJson("删除成功", "", response);
        } catch (SQLException e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("删除失败", response);
        }
    }

    protected void SendDateList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        List<Map<String, Object>> pros = null;
        try {
            String begin = request.getParameter("begin");
            String end = request.getParameter("end");

            pros = qr.query("select id,sdate from sendDate " +
                    "limit ?,?",new MapListHandler(),new Object[]{Integer.valueOf(begin),Integer.valueOf(end)});
            JsonUtils.writeSuccessJson("查询成功", pros, response);
        } catch (SQLException e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
    }



	protected void addHotelSendDate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		String sDate = request.getParameter("sdate");
		QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
		try {
			int i = qr.update("insert into t_hotel_senddate(sdate) values(?) ",new Object[]{sDate});
			JsonUtils.writeSuccessJson("添加成功", "", response);
		} catch (SQLException e) {
			e.printStackTrace();
			if (e.getErrorCode() == 1062)
				JsonUtils.writeBeanFailJson("该日期已存在", response);
			else
				JsonUtils.writeBeanFailJson("添加失败", response);
		}
	}
	protected void delHotelSendDate(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
		try {
			int i = qr.update("delete from t_hotel_senddate where id = ? ",new Object[]{Integer.valueOf(id)});
			JsonUtils.writeSuccessJson("删除成功", "", response);
		} catch (SQLException e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("删除失败", response);
		}
	}

	protected void HotelSendDateList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
		List<Map<String, Object>> pros = null;
		try {
			String begin = request.getParameter("begin");
			String end = request.getParameter("end");

			pros = qr.query("select id,sdate from t_hotel_senddate " +
					"limit ?,?",new MapListHandler(),new Object[]{Integer.valueOf(begin),Integer.valueOf(end)});
			JsonUtils.writeSuccessJson("查询成功", pros, response);
		} catch (SQLException e) {
			e.printStackTrace();
			JsonUtils.writeBeanFailJson("查询失败", response);
		}
	}



    protected void ProdcutClassList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        ProductTypeDao dao = new ProductTypeDao();

        List<Map<String, Object>> pros = null;
        try {
            String begin = request.getParameter("begin");
            String end = request.getParameter("end");
			Admin admin = (Admin) request.getSession().getAttribute("admin");
			String sql = "";
			if (admin.getCityId() != 0) {
				sql = "select * from productclass where cityId= " + admin.getCityId() + " limit ?,?";
			} else {
				sql = "select * from productclass limit ?,?";
			}
            pros = qr.query(sql, new MapListHandler(),new Object[]{Integer.valueOf(begin),Integer.valueOf(end)});
            JsonUtils.writeSuccessJson("查询成功", pros, response);
        } catch (SQLException e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
    }

    protected void addProdcutClass(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        ProductTypeDao dao = new ProductTypeDao();
        try {
            ProductClass productClass = WebUtils.write2bean(request,ProductClass.class);
            dao.add(productClass);
            JsonUtils.writeSuccessJson("查询成功", productClass, response);
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
    }

    protected void updateProdcutClass(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        ProductTypeDao dao = new ProductTypeDao();
        try {
            ProductClass productClass = WebUtils.write2bean(request,ProductClass.class);
            dao.update(productClass);
            JsonUtils.writeSuccessJson("更新成功", productClass, response);
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("更新失败", response);
        }
    }
    protected void delProdcutClass(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        ProductTypeDao dao = new ProductTypeDao();
        try {
            ProductClass productClass = WebUtils.write2bean(request,ProductClass.class);
            dao.del(productClass);
            JsonUtils.writeSuccessJson("删除成功", productClass, response);
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("删除失败", response);
        }
    }
    protected void prodcutClassdetail(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
//        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        ProductTypeDao dao = new ProductTypeDao();
//        Map<String, Object> pros = null;
        try {
            String id = request.getParameter("id");
//            pros = qr.query("select * from productclass where id = ?" ,new MapHandler(),new Object[]{Integer.valueOf(id)});
            Map<String,Object> map = new HashMap<>();
            map.put("id",Integer.valueOf(id));
            ProductClass productClass =  dao.findOne(map);
            JsonUtils.writeSuccessJson("查询成功", productClass, response);
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
    }
    protected void changePcOpenState(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        QueryRunner qr = new QueryRunner(C3p0DataSourceUtils.getDataSource());
        try {
            String id = request.getParameter("id");
            qr.update("UPDATE productclass SET isopen = IF(isopen=1,0,1) WHERE id = ?",new Object[]{Integer.valueOf(id)});
            JsonUtils.writeSuccessJson("查询成功","", response);
        } catch (Exception e) {
            e.printStackTrace();
            JsonUtils.writeBeanFailJson("查询失败", response);
        }
    }
}
